<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\admin\validate;

use app\admin\model\Admin;
use app\common\validate\BaseValidate;
use think\facade\Cache;

/**
 * 登录验证器
 */
class LoginValidate extends BaseValidate
{
    protected $rule = [
        'username' => 'require',
        'password' => 'require|password',
    ];

    protected $message = [
        'username.require' => '请输入用户名',
        'password.require' => '请输入密码'
    ];

    /**
     * 密码验证
     * @param $password
     * @param $other
     * @param $data
     * @return bool|string
     */
    public function password($password, $other, $data)
    {
        $adminCache = Cache::get('admin_login' . $data['username']);
        //后台账号安全机制，连续输错后锁定，防止账号密码暴力破解
        if (!$adminCache) {
            $adminCache = ['login_count' => 0];
        }
        if ($adminCache['login_count'] > 5) {
            return '密码错误次数过多，请稍后再试';
        }

        $adminInfo = Admin::where('username', '=', $data['username'])
            ->field(['password,status'])
            ->findOrEmpty();

        if ($adminInfo->isEmpty()) {
            return '用户名或密码错误';
        }

        if ($adminInfo['status'] === 0) {
            return '账号已禁用';
        }

        if (empty($adminInfo['password'])) {
            $adminCache['login_count'] = 0;
            Cache::set('admin_login' . $data['username'], $adminCache, 86400);
            return '用户名或密码错误';
        }

        if (!Admin::passwordVerify($password, $adminInfo['password'])) {
            $adminCache['login_count']++;
            Cache::set('admin_login' . $data['username'], $adminCache, 86400);
            return '用户名或密码错误';
        }

        $adminCache['login_count'] = 0;
        Cache::set('admin_login' . $data['username'], $adminCache, 86400);
        return true;
    }
}